package com.plan.code;

import java.util.Optional;

/**
 * @description: 策略模式优化if-else
 * @author: admin
 * @time: 2022/12/8 20:35
 */
public class IfElse04 {
    public static void main(String[] args) {
        String command = "aaa";
        int num1 = 5;
        int num2 = 4;
        //System.out.println(new Context(new Add()).execute(num1, num2));
        //这种方式还是需要跟工厂模式配合使用
        System.out.println(Optional.ofNullable(StrategyFactory.getPayStrategy(command))
                .orElse(Strategy::getPayStrategy)
                .execute(num1, num2));
    }
}

class StrategyFactory {
    public static Strategy getPayStrategy(String command) {
        try {
            // 1.获取枚举中className
            String className = EnumStrategy.valueOf(command).getClassName();
            // 2.使用java反射技术初始化类
            return (Strategy) Class.forName(className).newInstance();
        } catch (Exception e) {
            return null;
        }
    }
}

enum EnumStrategy {
    add("com.plan.code.Add"),
    sub("com.plan.code.Sub"),
    mul("com.plan.code.Mul"),
    div("com.plan.code.Div");

    /**
     * class完整地址
     */
    private String className;

    EnumStrategy(String className) {
        this.setClassName(className);
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }
}

/*class Context {
    private Strategy strategy;

    public Context() {
    }

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public int execute(int num1, int num2) {
        return strategy.execute(num1, num2);
    }
}*/

interface Strategy {
    int execute(int num1, int num2);

    static int getPayStrategy(int i, int i1) {
        return -1;
    }
}

class Add implements Strategy {
    @Override
    public int execute(int num1, int num2) {
        return num1 + num2;
    }
}

class Sub implements Strategy {
    @Override
    public int execute(int num1, int num2) {
        return num1 - num2;
    }
}

class Mul implements Strategy {
    @Override
    public int execute(int num1, int num2) {
        return num1 * num2;
    }
}

class Div implements Strategy {
    @Override
    public int execute(int num1, int num2) {
        return num1 / num2;
    }
}


